from flask_script import Manager
from flask_migrate import Migrate, MigrateCommand

from info.models import User

"""manager.py主程序入口只保留项目启动的流程"""

# 导入info包中创建app的函数和已经创建好的db对象
from info import create_app, db, models

# 利用info包中的create_app函数创建不同模式的app:development / production
app = create_app('development')

# [1]创建Manager对象,用Migrate关联app对象和数据库db对象
manager = Manager(app)
Migrate(app, db)
# [2]添加数据库迁移命令到manager对象中
manager.add_command('db', MigrateCommand)


# 创建管理员账号
@manager.option('-u', '-username', dest='username')
@manager.option('-p', '-password', dest='password')
def createsuperuser(username, password):
    """创建管理员:python manage.py createsuperuser -u xxx -p xxx"""
    if not all([password, username]):
        print('参数不足')
        return
    user = User()
    user.mobile = username
    user.nick_name = username
    user.password = password
    user.is_admin = True
    try:
        db.session.add(user)
        db.session.commit()
    except Exception as e:
        print(e)
        db.session.rollback()
    print('创建成功')


if __name__ == '__main__':
    # app.run()
    manager.run()
